﻿<template>
	<view class="app-container">
		<!-- 固定顶部导航栏 -->
		<view class="fixed-header" :style="fixedHeaderStyle">
			<!-- 状态栏占位 -->
			<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

			<!-- 标题导航栏 -->
			<view class="title-navbar" :style="titleNavbarStyle">
				<!-- 切换按钮容器 -->
				<view class="switch-container">
					<view v-for="(tab, index) in topTab" :key="index"
						:class="['switch-item', { active: topTabIndex === index }]" 
						:style="{ color: topTabIndex === index ? headerColor : '#ffffff' }"
						@click="changeTopTab({ index })">
						{{ tab.name }}
					</view>
					<!-- 滑动指示器 -->
					<view class="switch-indicator" :style="indicatorStyle"></view>
				</view>
			</view>

			<!-- 搜索框 -->
			<view class="search-container">
				<view class="search-select">
					<uni-data-select v-model="selectRangeData" :localdata="range" mode="none"
						:clear="false"></uni-data-select>
				</view>

				<u-search placeholder="输入搜索的关键词" v-model="searchKey" :showAction="false" height="40"></u-search>
				<!-- 					<button class="search-btn" @click="handleSearch">
						<SvgIcon name="search" :size="24" color="#666666" />
					</button> -->

			</view>

			<view class="nav-tabs card">
				<view v-for="(item, index) in navTabs" :key="index"
					:class="['tab-item', currentTab === item.value ? 'active' : '']" @click="changeTab(item.value)">
					{{ item.label }}

					<view class="tab-badge" v-if="item.badge">
						{{ item.badge }}
					</view>
				</view>
			</view>
		</view>

		<!-- 内容区域，添加顶部间距 -->
		<view class="content-area" :style="contentAreaStyle">
			<!-- 顶部导航栏 -->


			<!-- 产品展示区 -->
			<scroll-view scroll-y class="product-list">
				<!-- 待上架tab的特殊布局 -->
				<view v-if="currentTab === 2" class="pending-shelf-container">
					<!-- 遍历不同的产品类型 -->
					<view v-for="(originType, typeKey) in originTypeMap" :key="typeKey">
						<!-- 转换为数字类型进行匹配 -->
						<view v-if="groups[1][Number(typeKey)] && groups[1][Number(typeKey)].length > 0" class="group-container">
							<!-- 分组标题 -->
							<view class="group-header" @click="showPending = !showPending">
								<view class="group-title">
									<view class="title-bar" :style="{ backgroundColor: headerColor }"></view>
									<text class="title-text">{{ originType }}</text>
								</view>

								<uni-icons v-if="groups[1][Number(typeKey)].length > 1"
									:type="showPending ? 'bottom' : 'top'"></uni-icons>
							</view>

							<!-- 产品列表 -->
							<view class="group-products" v-show="showPending">
								<view v-for="(product, productIndex) in groups[1][Number(typeKey)]" :key="product.mainInfo.productSpu.id"
									class="product-card pending-shelf" v-show="showAllPending || productIndex === 0">
									<ProductCard :info="product" :showStatus="true"
										@tap="gotoProductInfo(product.mainInfo.productSpu.id)" />
									<!-- 待上架状态和操作按钮 -->
									<view class="pending-shelf-actions">
										<view class="status-text">平台审核中,请等待...</view>
										<view class="btn danger" @click="withdrawToDraft(product)">撤回草稿箱</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 已下架tab的特殊布局 -->
				<view v-else-if="currentTab === 3" class="delisted-container">
					<!-- 遍历不同的产品类型 -->
					<view v-for="(originType, typeKey) in originTypeMap" :key="typeKey">
						<!-- 只显示有产品的类型 -->
						<view v-if="groups[2][typeKey] && groups[2][typeKey].length > 0" class="group-container">
							<!-- 分组标题 -->
							<view class="group-header" @click="showADelisted = !showADelisted">
								<view class="group-title">
									<view class="title-bar" :style="{ backgroundColor: headerColor }"></view>
									<text class="title-text">{{ originType }}</text>
								</view>

								<uni-icons v-if="groups[2][typeKey].length > 1"
									:type="showADelisted ? 'bottom' : 'top'"></uni-icons>
							</view>

							<!-- 产品列表 -->
							<view class="group-products" v-show="showADelisted">
								<view v-for="product in groups[2][typeKey]" :key="product.mainInfo.productSpu.id"
									class="product-card delisted">
									<ProductCard :info="product"
										@tap="gotoProductInfo(product.mainInfo.productSpu.id)" />
									<!-- 已下架状态和操作按钮 -->
									<view class="delisted-actions">
										<view class="btn danger" @click="deleteProduct(product)">删除</view>
										<view class="btn success" @click="editProduct(product)">编辑</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 草稿箱tab的特殊布局 -->
				<view v-else-if="currentTab === 0" class="draft-container">
					<!-- 遍历不同的产品类型 -->
					<view v-for="(originType, typeKey) in originTypeMap" :key="typeKey">
						<!-- 只显示有产品的类型 -->
						<view v-if="groups[3][typeKey] && groups[3][typeKey].length > 0" class="group-container">
							<!-- 分组标题 -->
							<view class="group-header" @click="showADraft = !showADraft">
								<view class="group-title">
									<view class="title-bar" :style="{ backgroundColor: headerColor }"></view>
									<text class="title-text">{{ originType }}</text>
								</view>

								<uni-icons v-if="groups[3][typeKey].length > 1"
									:type="showADraft ? 'bottom' : 'top'"></uni-icons>
							</view>

							<!-- 产品列表 -->
							<view class="group-products" v-show="showADraft">
								<view v-for="product in groups[3][typeKey]" :key="product.mainInfo.productSpu.id"
									class="product-card draft">
									<ProductCard :info="product"
										@tap="gotoProductInfo(product.mainInfo.productSpu.id)" />
									<!-- 草稿箱操作按钮 -->
									<view class="draft-actions">
										<view class="btn danger" @click="deleteProduct(product)">删除</view>
										<view class="btn success" @click="editProduct(product)">编辑</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="no-data" v-if="!hasAnyData(groups[3])">
						<view class="no-data-text">
							暂无相关商品
						</view>
						<view class="no-data-btn" @click="navToPage()">
							创建商品
						</view>
					</view>
				</view>

				<!-- 其他tab的原有布局（售卖中） -->
				<view v-else class="draft-container">
					<!-- 遍历不同的产品类型 -->
					<view v-for="(originType, typeKey) in originTypeMap" :key="typeKey">
						<!-- 只显示有产品的类型 -->
						<view v-if="groups[0][typeKey] && groups[0][typeKey].length > 0" class="group-container">
							<!-- 分组标题 -->
							<view class="group-header" @click="showACooperation = !showACooperation">
								<view class="group-title">
									<view class="title-bar" :style="{ backgroundColor: headerColor }"></view>
									<text class="title-text">{{ originType }}</text>
								</view>

								<uni-icons v-if="groups[0][typeKey].length > 1"
									:type="showACooperation ? 'bottom' : 'top'"></uni-icons>
							</view>

							<!-- 产品列表 -->
							<view v-show="showACooperation" v-for="product in groups[0][typeKey]"
								:key="product.mainInfo.productSpu.id" class="product-card draft">
								<ProductCard :info="product" @tap="gotoProductInfo(product.mainInfo.productSpu.id)" />
								<!-- 统一的操作按钮容器，横向排列 -->
								<view class="operate-btns">
									<!-- 在草稿箱时编辑和删除按钮 -->
									<view v-if="currentTab === 0" class="btn-group">
										<view class="btn success" @click="editProduct(product)">编辑</view>
										<view class="btn danger" @click="deleteProduct(product)">删除</view>
									</view>

									<!-- 提交审核按钮 -->
									<view v-if="currentTab === 0">
										<view class="btn warning" @click="submitAudit(product)">提交审核</view>
									</view>
									<!-- 撤销审核按钮 -->
									<view v-if="currentTab === 1">
										<view class="btn warning" @click="cancelAudit(product)">撤销审核</view>
									</view>

									<!-- 上架按钮 -->
									<view v-if="currentTab === 2 || currentTab === 3">
										<view class="btn success" @click="onShelf(product)">上架</view>
									</view>

									<!-- 下架班期管理按钮 -->
									<view v-if="currentTab === 4" class="btn-group">
										<view class="btn cooperation" @click="manageCooperation(product)"
											:style="{ color: headerColor, border: '1px solid ' + headerColor }">
											合作申请管理
											<!-- 										<view class="badge" v-if="product.cooperationCount > 0">
										{{ product.cooperationCount}}
										</view> -->

											<view class="badge">
												6
											</view>
										</view>
										<view class="btn success" @click="copyToDraft(product)">复制到草稿</view>
										<view class="btn danger" @click="offShelf(product)">下架</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="no-data" v-if="!hasAnyData(groups[0])">
						<view class="no-data-text">
							暂无相关商品
						</view>
						<view class="no-data-btn" @click="navToPage()">
							创建商品
						</view>
					</view>
				</view>
				<!-- 			<view class="empty-tip" v-if="(groups[0][1].length + groups[0][2].length + groups[0][3].length) == 0" >
				<text class="empty-text">暂无相关商品</text>
				<up-button type="primary" size="default" style="margin-top: 30rpx;"
					@click="navigateToCreateProduct">创建商品</up-button>
			</view> -->
			</scroll-view>
			<!-- 无商品提示 -->

			<!-- 全局TabBar -->
			<global-tab-bar />
		</view>
	</view>
</template>

<script>
import GlobalTopNav from '@/components/GlobalTopNav.vue'
import GlobalTabBar from '@/components/GlobalTabBar.vue'
import ProductCard from '@/components/ProductCard.vue'
import { request } from '@/utils/request.js'
import { mergeAllProducts } from '@/utils/productUtil.js'
import { useUserStore } from '@/store'


export default {
	components: {
		GlobalTopNav,
		GlobalTabBar,
		ProductCard
	},
	data() {
		return {
			// 使用缓存的导航栏高度
			statusBarHeight: 0,
			navbarTotalHeight: 0,
			navbarHeight: 0,

			// 头部颜色相关
			headerColor: '#39B54A', // 默认绿色
			bgColor: '#fff', // 默认绿色
			businessType: 1, // 默认业务类型
			topTab: [
				{ name: '货架' },
				{ name: '橱窗' }
			],
			topTabIndex: 0,
			searchKey: '',
			currentTab: 4,
			range: [],
			selectRangeData: "全部类型",
			navTabs: [
				{ label: '售卖中', value: 4 },
				{ label: '待上架', value: 2 },
				{ label: '已下架', value: 3 },
				{ label: '草稿箱', value: 0 },
				{ label: '新建', value: -1 }
			],
			statusMap: {
				0: '草稿箱',
				1: '审核中',
				2: '待上架',
				3: '已下架',
				4: '售卖中'
			},
			// 产品类型映射
			originTypeMap: {
				1: '泛营地接待',
				2: '综合研学业务',
				3: '目的地接待',
				4: '组团业务',
				5: '研学活动'
			},
			products: [
				{
					id: 1001,
					name: '苹果手机',
					main_image: 'https://img.yzcdn.cn/vant/apple-1.jpg',
					status: 4
				}
			],
			// 页面切换状态
			TabCur: 1, // 0: 店铺, 1: 货架
			swiper_current: 0,
			// 主标签数据 - 店铺/货架
			mainTabs: [
				{ name: '店铺' },
				{ name: '货架' }
			],
			// 店铺内容标签数据
			contentTabs: [
				{ name: '服务/商品' },
				{ name: '指导团队' },
				{ name: '备用栏目' },
				{ name: '学员评价' }
			],
			// 货架产品状态标签数据
			productTabs: [],
			// 搜索和筛选
			selectData: ['全部类型', '研学接待', '门票零售', '旅游团票'],
			index: 0,
			parm: '',
			// 标签索引
			tabIndex: 0,
			TabCur1: 0,
			// 数据
			companyInfo: {},
			CommentList: [],
			ProjectList: [],
			UsersList: [],
			newProductList: [],
			loading: false,
			groups: {
				0: { 1: [], 2: [], 3: [] }, // 售卖中按 originType 分组
				1: { 1: [], 2: [], 3: [] }, // 待上架按 originType 分组
				2: { 1: [], 2: [], 3: [] }, // 已下架按 originType 分组
				3: { 1: [], 2: [], 3: [] }  // 草稿箱按 originType 分组
			},
			showADraft: true,
			showACooperation: true,
			showADelisted: true,
			showPending: true,
		}
	},
	onLoad() {
		// 设置用户角色为商家
		const userStore = useUserStore();
		userStore.setRole('merchant');

		// 获取缓存的导航栏高度
		this.initNavbarHeight();

		// 设置头部颜色
		this.setHeaderColor();

		// 初始化产品标签数据
		this.productTabs = [
			{ id: 4, name: '售卖中', badge: 0 },
			{ id: 2, name: '待上架', badge: 0 },
			{ id: 3, name: '已下架', badge: 0 },
			{ id: 0, name: '草稿箱', badge: 0 },
			{ id: 5, name: '新建', badge: 0 }
		]



		this.getCI()


		console.log(666, this.productTabs)
	},
	//每次页面显示时执行
	onShow() {
		this.getCI()
	},
	computed: {
		filteredProducts() {
			if (this.currentTab === -1) return []
			// 根据当前标签页显示对应的产品组
			const statusMap = {
				4: 0, // 售卖中 - 对应 groups[0]
				2: 1, // 待上架 - 对应 groups[1]
				3: 2, // 已下架 - 对应 groups[2]
				0: 3  // 草稿箱 - 对应 groups[3]
			};
			const groupIndex = statusMap[this.currentTab];
			if (groupIndex !== undefined && this.groups[groupIndex]) {
				// 合并所有 originType 的产品
				const allProducts = [];
				Object.values(this.groups[groupIndex]).forEach(products => {
					if (Array.isArray(products)) {
						allProducts.push(...products);
					}
				});
				return allProducts;
			}
			return [];
		},

		// 固定头部样式
		fixedHeaderStyle() {
			return {
				position: 'fixed',
				top: 0,
				left: 0,
				right: 0,
				zIndex: 999,
				backgroundColor: '#ffffff',
			}
		},

		// 标题导航栏样式
		titleNavbarStyle() {
			return {
				height: this.navbarHeight + 'px',
				display: 'flex',
				alignItems: 'center',
				justifyContent: 'center',
				backgroundColor: '#ffffff'
			}
		},

		// 内容区域样式
		contentAreaStyle() {
			return {
				paddingTop: (this.navbarTotalHeight + 60 + 45) + 'px'
			}
		},

		// 滑动指示器样式
	indicatorStyle() {
		const itemWidth = 100 / this.topTab.length // 每个按钮的宽度百分比
		return {
			left: (this.topTabIndex * itemWidth) + '%',
			width: `calc(${itemWidth}% - 8rpx)`,
			marginLeft: '4rpx'
		}
	}
	},
	methods: {
		// 初始化导航栏高度
		initNavbarHeight() {
			// 使用全局注册的navbarUtil方法
			this.statusBarHeight = this.$navbarUtil.getStatusBarHeight()
			this.navbarHeight = this.$navbarUtil.getNavbarHeight()
			this.navbarTotalHeight = this.$navbarUtil.getNavbarTotalHeight()

			console.log('商户页面 - 导航栏高度:', {
				statusBarHeight: this.statusBarHeight,
				navbarHeight: this.navbarHeight,
				navbarTotalHeight: this.navbarTotalHeight
			})
		},

		hasAnyData(obj) {
			return Object.values(obj).some(arr => Array.isArray(arr) && arr.length > 0);
		},

		// 设置头部颜色
		setHeaderColor() {
			const companyInfo = uni.getStorageSync('companyInfo');
			console.log('商户页面 - 获取companyInfo:', companyInfo);

			if (companyInfo && companyInfo.businessType !== undefined && companyInfo.businessType !== null) {
				this.businessType = companyInfo.businessType;
				console.log('商户页面 - businessType:', this.businessType);

				switch (this.businessType) {
					case 1:
						this.headerColor = '#0081FF'; // 蓝色
						this.bgColor = '#0081FF1A'
						console.log('商户页面 - 设置为蓝色');

						this.range = [
							{ value: "全部类型", text: "全部类型" },
							{ value: "研学接待", text: "研学接待" },
							{ value: "研学团票", text: "研学团票" },
							{ value: "门票零售", text: "门票零售" },
						]
						break;
					case 2:
						this.headerColor = '#38B03F'; // 绿色
						this.bgColor = '#39B54A1A'
						console.log('商户页面 - 设置为绿色');
						this.range = [
							{ value: "全部类型", text: "全部类型" },
							{ value: "地接业务", text: "地接业务" },
							{ value: "组团业务", text: "组团业务" },
							{ value: "综合研学", text: "综合研学" },
						]
						break;
					case 3:
						this.headerColor = '#F37B1D'; // 黄色
						this.bgColor = '#F37B1D1A'
						console.log('商户页面 - 设置为黄色');
						this.range = [
							{ value: "全部类型", text: "全部类型" },
							{ value: "研学活动", text: "研学活动" },
							{ value: "课程类", text: "课程类" },
							{ value: "服务类", text: "服务类" },
						]
						break;
					default:
						this.headerColor = '#39B54A'; // 默认绿色
						console.log('商户页面 - 设置为默认绿色');
						this.range = [];
						break;
				}
				console.log('商户页面 - 最终头部颜色:', this.headerColor);
			} else {
				console.log('商户页面 - companyInfo或businessType不存在，使用默认颜色');
				this.headerColor = '#39B54A'; // 默认绿色
			}
		},

		changeTopTab(e) {
			console.log('topTab change', e.index)
			this.topTabIndex = e.index
			if (e.index === 0) {
				// 店铺
				uni.redirectTo({ url: '/pages/merchant/index/index' })
			} else {
				// 货架
				uni.redirectTo({ url: '/public/merchant/shop' })
			}
		},
		handleSearch() {
			uni.showToast({ title: '搜索：' + this.searchKey, icon: 'none' })
		},
		changeTab(val) {
			if (val !== -1) {
				this.currentTab = val
				return
			}
			// 新建时显示弹窗提示
			// uni.showModal({
			// 	title: '提示',
			// 	content: '新建功能开发中，敬请期待！',
			// 	showCancel: false,
			// 	confirmText: '确定'
			// })
			// 进行跳转弹窗
			uni.navigateTo({
				url: '/public/merchant/businessSelection/businessSelection'
			})
		},
		navToPage() {
			if (this.businessType == 1 || this.businessType == 2) {
				uni.navigateTo({
					url: '/public/merchant/businessSelection/businessSelection'
				})
			} else if (this.businessType == 3) {
				uni.navigateTo({
					url: '/pages/merchant/category/index'
				});
			}
		},
		//编辑产品
		editProduct(product) {
			console.log('编辑产品:', product)
			// 跳转到编辑页面
			uni.navigateTo({ url: `/public/create/index?id=${product.mainInfo.productSpu.id}&mode='edit'` })
		},
		onShelf(product) {
			uni.showToast({ title: `${product.name} 已上架`, icon: 'success' })
			product.status = 4
		},
		offShelf(product) {
			uni.showToast({ title: `${product.name} 已下架`, icon: 'none' })
			product.status = 3
		},
		// 班期管理
		managePeriods(product) {
			console.log('班期管理', product);
			const id = product.mainInfo.productSpu.id
			uni.navigateTo({ url: `/public/campManagement/campManagement?id=${id}` })
		},
		// 合作申请管理
		manageCooperation(product) {
			console.log('合作申请管理', product);
			const id = product.mainInfo.productSpu.id
			console.log('准备跳转到合作申请管理页面，产品ID:', id)
			// 这里可以跳转到合作申请管理页面，您可以根据实际需求修改URL
			uni.navigateTo({
				url: `/public/cooperation/cooperation?id=${id}`,
				success: () => {
					console.log('页面跳转成功')
				},
				fail: (err) => {
					console.error('页面跳转失败:', err)
				}
			})
		},
		//查看自己的产品详情
		gotoProductInfo(productId) {
			uni.navigateTo({
				url: `/public/productInfo/productInfo?spuId=${productId}&mode=detail`
			})
		},
		// 获取商家信息
		async getCI() {
			this.loading = true
			try {
				const res = await request({
					url: `/merchant/query`,
					method: 'GET'
				})

				if (res.code === 200) {
					const companyInfo = res.data
					// 处理图片数据
					if (companyInfo === null || companyInfo.id === null) {
						uni.showModal({
							title: '提示',
							content: '您还未注册商家，请先注册商家',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/public/merchantRegister/merchantRegister'
									})
								}
								if (res.cancel) {
									uni.switchTab({ url: '/pages/customer/mine/index' })
									uni.showToast({ title: '取消注册', icon: 'none' })
								}
							}
						})
					}
					this.companyInfo = companyInfo
					// 存储到本地
					uni.setStorageSync('companyInfo', companyInfo)
					// 获取产品数据
					this.getProduct()
					// 获取商家内容
					// this.getContent(companyInfo.CID)
				}
			} catch (error) {
				console.error('获取商家信息失败:', error)
				uni.showToast({ title: '获取商家信息失败', icon: 'none' })
			} finally {
				this.loading = false
			}
		},

		// 获取产品数据
		async getProduct() {
			try {
				const merchantInfo = uni.getStorageSync('companyInfo')
				let url = `/product-spu/getClassFirst`
				if (merchantInfo.businessType === 2) {
					url = `/product-spu/getClassSecond`
				} else if (merchantInfo.businessType === 3) {
					url = `/product-spu/getClassThird`
				}

				const res = await request({
					url: `${url}?merchantId=${merchantInfo.id}`,
					method: 'GET'
				})

				if (res.code === 200) {
					const product = res.data
					console.log('获取到的原始产品数据:', product)

					// 检查数据是否为空
					if (!product || (Array.isArray(product) && product.length === 0)) {
						console.log('产品数据为空')
						// 重置分组为空数组
						// 🔑 初始化所有可能的产品类型（1-5）
						this.groups = {
							0: { 1: [], 2: [], 3: [], 4: [], 5: [] },
							1: { 1: [], 2: [], 3: [], 4: [], 5: [] },
							2: { 1: [], 2: [], 3: [], 4: [], 5: [] },
							3: { 1: [], 2: [], 3: [], 4: [], 5: [] }
						}
						console.log('this.groups', this.groups)
						// 重置标签数量
						if (this.productTabs && this.productTabs.length > 0) {
							this.productTabs[0].badge = 0
							this.productTabs[1].badge = 0
							this.productTabs[2].badge = 0
							this.productTabs[3].badge = 0
							this.productTabs[4].badge = 0
						}
						return
					}

					// 使用productUtil合并产品数据
					// 🔑 商家查看自己的产品，不传固定的productType，让mergeAllProducts从数据中自动提取
					// 这样可以确保：
					// - B1商家看到自己的 产品
					// - B2商家看到自己的 产品
					// - B3商家看到自己的 产品
					const newProductList = mergeAllProducts(product)
					console.log('合并后的产品列表:', newProductList)
					console.log('产品数量:', newProductList.length)

					// 状态字符串到数字的映射
					const statusStringToNumber = {
						'草稿箱': 0,
						'审核中': 1,
						'待上架': 2,
						'已下架': 3,
						'售卖中': 4
					}

					// 定义状态映射关系（产品状态：0-草稿箱, 1-审核中, 2-待上架, 3-已下架, 4-售卖中）
					// 将状态码映射到groups索引
					const statusToGroupMap = {
						4: 0, // 售卖中 - status=4 放入 groups[0]
						1: 1, // 审核中 - status=1 放入 groups[1]（待上架）
						2: 1, // 待上架 - status=2 放入 groups[1]
						3: 2, // 已下架 - status=3 放入 groups[2]
						0: 3  // 草稿箱 - status=0 放入 groups[3]
					}

					// 初始化目标分组 - 每个状态下按 originType 再分组
					// 🔑 初始化所有可能的产品类型（1-5），避免类型不匹配问题
					const groups = {
						0: { 1: [], 2: [], 3: [], 4: [], 5: [] }, // 售卖中按 originType 分组
						1: { 1: [], 2: [], 3: [], 4: [], 5: [] }, // 待上架按 originType 分组
						2: { 1: [], 2: [], 3: [], 4: [], 5: [] }, // 已下架按 originType 分组
						3: { 1: [], 2: [], 3: [], 4: [], 5: [] }  // 草稿箱按 originType 分组
					}

					// 遍历数组，按映射规则分组
					newProductList.forEach((item, index) => {
						// 检查数据结构
						if (!item || !item.mainInfo || !item.mainInfo.productSpu) {
							return
						}

						let originalStatus = item.mainInfo.productSpu.status

						// 如果状态是字符串，转换为数字
						if (typeof originalStatus === 'string') {
							const numStatus = statusStringToNumber[originalStatus]
							if (numStatus !== undefined) {
								originalStatus = numStatus
							} else {
								return
							}
						}

						// 将状态码映射到groups索引
						if (Object.prototype.hasOwnProperty.call(statusToGroupMap, originalStatus)) {
							const targetGroup = statusToGroupMap[originalStatus]
							// 获取产品的 productType，默认为1
							const originType = item.mainInfo.productSpu.productType || 1
							// 🔑 确保 originType 是数字类型，并且是有效的产品类型（1-5）
							const typeKey = Number(originType)
							if (typeKey >= 1 && typeKey <= 5) {
								// 按 productType 二级分组
								if (!groups[targetGroup][typeKey]) {
									groups[targetGroup][typeKey] = []
								}
								groups[targetGroup][typeKey].push(item)
							} else {
								console.warn(`产品 ${index} 的 productType ${originType} 不在有效范围内（期望: 1-5）`)
							}
						} else {
							console.warn(`产品 ${index} 的状态 ${originalStatus} 不在映射表中（期望: 0,1,2,3,4）`)
						}
					})
					console.log('分组结果:', groups)

					// 计算每个状态下所有 originType 的产品总数
					const getGroupTotal = (group) => {
						return Object.values(group).reduce((sum, arr) => sum + arr.length, 0)
					}

					console.log('分组统计:', {
						售卖中: getGroupTotal(groups[0]),
						待上架: getGroupTotal(groups[1]),
						已下架: getGroupTotal(groups[2]),
						草稿箱: getGroupTotal(groups[3])
					})

					// 更新标签数量 (根据productTabs的id来匹配groups)
					if (this.productTabs && this.productTabs.length > 0) {
						this.productTabs[0].badge = getGroupTotal(groups[0])  // 售卖中 - status=4
						this.productTabs[1].badge = getGroupTotal(groups[1])  // 待上架 - status=2
						this.productTabs[2].badge = getGroupTotal(groups[2])  // 已下架 - status=3
						this.productTabs[3].badge = getGroupTotal(groups[3])  // 草稿箱 - status=0
						this.productTabs[4].badge = 0  // 新建

						this.navTabs = this.navTabs.map((tab, index) => {
							return {
								...tab,
								badge: this.productTabs[index]?.badge || 0
							};
						});

					}

					console.log(21312, this.navTabs)

					// 更新groups
					this.groups = groups
					console.log('最终 groups:', this.groups)
				}
			} catch (error) {
				console.error('获取产品数据失败:', error)
				uni.showToast({ title: '获取产品数据失败', icon: 'none' })
			}
		},

		// 获取商家内容（评论、项目、用户）
		async getContent(id) {
			try {
				const res = await request({
					url: `/Company/GetCompany_ContentQuery?id=${id}&type=4`,
					method: 'GET'
				})

				const data = typeof res.data.body === 'string' ? JSON.parse(res.data.body) : res.data.body
				if (data) {
					this.CommentList = data.CommentList || []
					this.ProjectList = data.ProjectList || []
					this.UsersList = data.UsersList || []
				}
			} catch (error) {
				console.error('获取商家内容失败:', error)
			}
		},

		// 主标签（店铺/货架）切换
		onMainTabChange(index) {
			this.TabCur = index
		},

		// 店铺内容标签切换
		onContentTabChange(index) {
			this.tabIndex = index
		},

		// 货架产品标签切换
		onProductTabChange(index) {
			this.TabCur1 = index
			// 新建产品
			if (index === 4) {
				// 重置选中状态，避免从新建页面返回后仍然选中"新建"标签
				setTimeout(() => {
					this.TabCur1 = 0
				}, 100)
				// 跳转到新建页面
				uni.navigateTo({
					url: '/public/create/index',
					success: () => {
						console.log('成功跳转到新建页面')
					},
					fail: (err) => {
						console.error('跳转到新建页面失败:', err)
						uni.showToast({ title: '跳转失败，请重试', icon: 'none' })
					}
				})
			}
		},

		// 轮播图切换
		Swiperchange(e) {
			this.swiper_current = e.detail.current
		},

		// 切换到公司信息页面
		toCompanyInfo() {
			uni.navigateTo({ url: '/public/merchant/merchantInfo' })
		},

		// 拨打电话
		callPhone() {
			if (this.companyInfo.ContactPhone) {
				uni.makePhoneCall({
					phoneNumber: this.companyInfo.ContactPhone
				})
			}
		},

		// 查看项目详情
		viewProjectDetail(item) {
			uni.navigateTo({ url: `/public/productInfo/productInfo?id=${item.ID}` })
		},

		// 查看产品详情
		lookProductDetail(item) {
			uni.navigateTo({ url: `/public/productInfo/productInfo?id=${item.mainInfo.productSpu.id}` })
		},

		// 班期管理
		managePeriod(item) {
			uni.navigateTo({ url: `/public/period/period?id=${item.mainInfo.productSpu.id}` })
		},

		// 复制到草稿
		copyToDraft(item) {
			request({
				url: `/product-spu/copy?id=${item.mainInfo.productSpu.id}`,
				method: 'POST'
			}).then(() => {
				this.getProduct()
				uni.showToast({ title: '复制到草稿成功', icon: 'success' })
			}).catch(error => {
				console.error('复制到草稿失败:', error)
				uni.showToast({ title: '复制失败，请重试', icon: 'none' })
			})
		},

		// 撤回草稿箱
		withdrawToDraft(product) {
			console.log('撤回草稿箱', product)
			uni.showModal({
				title: '确认撤回',
				content: '确定要将此产品撤回草稿箱吗？',
				success: (res) => {
					if (res.confirm) {
						// 调用更新状态接口，将状态改为0（草稿箱）
						request({
							url: `/product-spu/updateStatus?spuId=${product.mainInfo.productSpu.id}&status=0`,
							method: 'POST'
						}).then(() => {
							// 更新本地状态
							product.mainInfo.productSpu.status = 0;
							// 刷新列表
							this.getProduct()
							uni.showToast({ title: '已撤回草稿箱', icon: 'success' })
						}).catch(error => {
							console.error('撤回草稿箱失败:', error)
							uni.showToast({ title: '撤回失败，请重试', icon: 'none' })
						})
					}
				}
			})
		},

		// 下架产品
		offShelf(item) {
			uni.showModal({
				title: '确认下架',
				content: '确定要下架该产品吗？',
				success: (res) => {
					if (res.confirm) {
						// 调用下架API
						request({
							url: `/product-spu/updateStatus?spuId=${item.mainInfo.productSpu.id}&status=3`,
							method: 'POST'
						}).then(() => {
							item.mainInfo.productSpu.status = 3
							// 刷新列表
							this.getProduct()
							uni.showToast({ title: '产品已下架', icon: 'success' })
						}).catch(error => {
							console.error('下架产品失败:', error)
							uni.showToast({ title: '下架失败，请重试', icon: 'none' })
						})
					}
				}
			})
		},
		/**
		 * 跳转到创建商品页面
		 */
		navigateToCreateProduct() {
			let businessType = uni.getStorageSync('companyInfo').businessType
			let url = '/public/create/index?mode=create'
			if (businessType == 3) url = '/pages/merchant/category/index'
			uni.navigateTo({
				url: url
			});
		},


		// 上架产品
		onShelf(item) {
			const companyInfo = uni.getStorageSync('companyInfo') || {}
			const businessType = companyInfo.businessType

			// businessType: 1-地接社/场馆，2-旅行社，3-教培
			if (businessType === 2 || businessType === 3) {
				// 旅行社和教培：跳转到产品详情页，选择班期后申请调用
				console.log('旅行社/教培模式，跳转到产品详情页选择班期')
				uni.navigateTo({
					url: `/public/productInfo/productInfo?id=${item.mainInfo.productSpu.id}`
				})
			} else {
				// 地接社/场馆：跳转到创建班期页面
				console.log('地接社模式，跳转到创建班期页面')
				uni.navigateTo({
					url: `/public/period/periodCreate?id=${item.mainInfo.productSpu.id}`
				})
			}
		},

		// 提交审核
		submitAudit(product) {
			uni.showModal({
				title: '提交审核',
				content: '确定要提交该产品进行审核吗？',
				success: (res) => {
					if (res.confirm) {
						// 根据传入的参数结构获取正确的ID
						const spuId = product.mainInfo ? product.mainInfo.productSpu.id : product.id;
						// 使用统一的状态更新接口
						request({
							url: `/product-spu/updateStatus?spuId=${spuId}&status=1`,
							method: 'POST'
						}).then(() => {
							// 更新本地状态
							if (product.mainInfo) {
								product.mainInfo.productSpu.status = 1;
							} else {
								product.status = 1;
							}
							// 刷新列表
							this.getProduct()
							uni.showToast({ title: '已提交审核', icon: 'success' })
						}).catch(error => {
							console.error('提交审核失败:', error)
							uni.showToast({ title: '提交失败，请重试', icon: 'none' })
						})
					}
				}
			})
		},
		// 撤销审核
		cancelAudit(product) {
			uni.showModal({
				title: '撤销审核',
				content: '确定要撤销审核吗？',
				success: async (res) => {
					if (res.confirm) {
						// 根据传入的参数结构获取正确的ID
						const spuId = product.mainInfo ? product.mainInfo.productSpu.id : product.id;
						// 使用统一的状态更新接口
						request({
							url: `/product-spu/updateStatus?spuId=${spuId}&status=0`,
							method: 'POST'
						}).then(() => {
							// 更新本地状态
							if (product.mainInfo) {
								product.mainInfo.productSpu.status = 0;
							} else {
								product.status = 0;
							}
							// 刷新列表
							this.getProduct()
							uni.showToast({ title: '已撤销审核', icon: 'success' })
						}).catch(error => {
							console.error('撤销审核失败:', error)
							uni.showToast({ title: '撤销失败，请重试', icon: 'none' })
						})
					}
				}
			})
		},

		// 删除产品
		deleteProduct(item) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除该产品吗？删除后无法恢复。',
				success: (res) => {
					if (res.confirm) {
						// 调用删除API
						request({
							url: `/product-spu/remove?spuId=${item.mainInfo.productSpu.id}`,
							method: 'POST'
						}).then(() => {
							// 刷新列表
							this.getProduct()
							uni.showToast({ title: '产品已删除', icon: 'success' })
						}).catch(error => {
							console.error('删除产品失败:', error)
							uni.showToast({ title: '该商品已被调用，无法删除', icon: 'none' })
						})
					}
				}
			})
		},

		// 搜索功能
		bindconfirm() {
			console.log('搜索关键词:', this.parm)
			// 根据关键词过滤产品列表
			this.getProduct() // 实际项目中应传递搜索参数
		},

		// 类型选择
		selectTap() {
			const options = this.selectData
			uni.showActionSheet({
				itemList: options,
				success: (res) => {
					this.index = res.tapIndex
					console.log('当前选择类型:', this.selectData[this.index])
					// 根据选择的类型刷新产品列表
					this.getProduct() // 实际项目中应传递类型参数
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.app-container {
	display: flex;
	flex-direction: column;
	background: #f5f5f5;
	min-height: 100vh;
}

/* 固定头部样式 */
.fixed-header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: #ffffff;
}

.status-bar {
	width: 100%;
	background-color: inherit;
}

/* 标题导航栏样式 */
.title-navbar {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #ffffff;
}

.switch-container {
	position: relative;
	display: flex;
	width: 200rpx;
	height: 60rpx;
	background-color: v-bind(headerColor);
	border-radius: 30rpx;
	overflow: hidden;
}

.switch-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #ffffff;
	transition: all 0.3s ease;
	position: relative;
	z-index: 2;

}

.switch-item.active {
	color: v-bind(headerColor);
	font-weight: 600;
}

.switch-indicator {
	position: absolute;
	top: 6rpx;
	height: calc(100% - 10rpx);
	background-color: #ffffff;
	border-radius: 28rpx;
	transition: all 0.3s ease;
	z-index: 1;
}

/* 搜索容器样式 */
.search-container {
	height: 60px;
	padding: 0 20rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	gap: 10px;
}

.search-select {
	width: 100px;
}

.search-select ::v-deep .uni-select {
	font-size: 16px;
	color: #333;
}


.input-field {
	flex: 1;
	height: 100%;
	font-size: 28rpx;
	color: #333333;
	background: transparent;
	border: none;
	outline: none;
	line-height: 1.4;

	/* 兼容不同设备的高度 */
}

.input-field::-webkit-input-placeholder {
	line-height: 1.4;
}

.input-field::-moz-placeholder {
	line-height: 1.4;
}

.input-field:-ms-input-placeholder {
	line-height: 1.4;
}

.search-btn {
	width: 60rpx;
	height: 60rpx;
	background-color: transparent;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	transition: all 0.3s ease;
	flex-shrink: 0;

}

.search-btn:active {
	background-color: #e0e0e0;
	transform: scale(0.95);
}

/* 内容区域样式 */
.content-area {
	padding-top: 0;
	/* 由computed动态设置 */
}

/* 通用卡片样式 */
.card {
	background: #fff;

	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);

}

/* 搜索框 */
.search-box {
	margin-top: 20rpx;
	padding: 20rpx;

	.search-input {
		display: flex;
		align-items: center;
		background: #f9f9f9;
		border-radius: 40rpx;
		padding: 0 10rpx;

		.input-inner {
			flex: 1;
			height: 60rpx;
			padding-left: 20rpx;
			font-size: 26rpx;
		}

		.search-btn {
			background: #007aff;
			color: #fff;
			font-size: 26rpx;
			border-radius: 40rpx;
			padding: 0 28rpx;
			margin-left: 10rpx;
			height: 60rpx;
			line-height: 60rpx;
		}
	}
}

/* 顶部导航栏 Tabs */
.nav-tabs {
	display: flex;
	height: 45px;

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		padding: 20rpx 0;
		color: #666;
		transition: all 0.2s;
		position: relative;

	}

	.tab-item.active {
		color: v-bind(headerColor);
		font-weight: 600;
		border-bottom: 6rpx solid v-bind(headerColor);
	}
}

/* 产品列表 */
.product-list {

	padding: 0 0 160rpx 0;
	min-height: 100vh;
	// width: calc(100% - 40rpx);
}

.product-card {
	background: #fff;

	padding: 20rpx;
	margin-bottom: 20rpx;

}

/* 操作按钮样式 */
.operate-btns {
	display: flex;
	flex-wrap: wrap;
	gap: 12rpx;
	margin-top: 20rpx;
	padding-top: 20rpx;
	// border-top: 1rpx solid #eee;
}

.btn {
	min-width: 150rpx;
	height: 64rpx;
	line-height: 64rpx;
	text-align: center;
	font-size: 24rpx;
	border-radius: 8rpx;
	padding: 0 16rpx;
	white-space: nowrap;
	border: none;
	font-weight: 500;
}

/* 按钮组样式 */
.btn-group {
	display: flex;
	flex: 1;
	gap: 16rpx;
	align-items: center;
	justify-content: space-between;
}


/* 合作申请管理按钮样式 */
.btn.cooperation {
	background-color: #fff;
	color: #0081FF;
	border: 1px solid #0081FF;
	position: relative;
	border-radius: 32rpx;
	font-weight: 400;
	font-size: 24rpx;
	height: 64rpx;
	line-height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 徽章样式 */
.badge {
	position: absolute;
	top: -4rpx;
	right: -4rpx;
	background-color: #ff3b30;
	color: #ffffff;
	border-radius: 50%;
	width: 28rpx;
	height: 28rpx;
	font-size: 16rpx;
	line-height: 28rpx;
	text-align: center;
	min-width: 24rpx;
	font-weight: 600;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 徽章样式 */
.tab-badge {
	position: absolute;
	top: 0rpx;
	right: 0rpx;
	background-color: #ff3b30;
	color: #ffffff;
	border-radius: 50%;
	width: 28rpx;
	height: 28rpx;
	font-size: 16rpx;
	line-height: 28rpx;
	text-align: center;
	min-width: 24rpx;
	font-weight: 600;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 不同功能按钮的颜色 */
.btn.primary {
	background-color: #007aff;
	color: white;
}

.btn.secondary {

	background-color: #5ac8fa;
	color: white;
}

.btn.success {
	border-radius: 32rpx;
	height: 64rpx;
	background-color: transparent;
	color: #787878;
	border: 1rpx solid #787878;
}

.btn.danger {
	border-radius: 32rpx;
	height: 64rpx;
	background-color: transparent;
	color: #787878;
	border: 1rpx solid #787878;
}

.btn.warning {
	background-color: #ff9500;
	color: white;
}

.btn.info {
	background-color: #5856d6;
	color: white;
}

/* 按钮点击效果 */
.btn:active {
	opacity: 0.8;
	transform: scale(0.98);
}

/* 空状态提示 */
.empty-tip {
	text-align: center;
	padding: 120rpx 0;
	color: #aaa;
	font-size: 28rpx;
}

/* 待上架特殊布局 */
.pending-shelf-container {
	margin: 20rpx;
}

.group-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 20rpx 20rpx 20rpx;

}

.group-title {
	display: flex;
	align-items: center;
}

.title-bar {
	width: 10rpx;
	height: 32rpx;
	background-color: #FF8C00;
	margin-right: 12rpx;
	border-radius: 5rpx;
}

.title-text {
	font-size: 32rpx;
	color: #333;
	font-weight: 600;
}

.collapse-icon {
	font-size: 24rpx;
	color: #999;
}

.group-products {
	background: white;
	border-radius: 12rpx;
	overflow: hidden;
}

.pending-shelf {
	margin-bottom: 0;
	border-bottom: 1rpx dashed #ccc;
}

.pending-shelf:last-child {
	border-bottom: none;
}

.pending-shelf-actions {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 24rpx;

}

.status-text {
	font-size: 24rpx;
	color: #666;
}

.btn.danger-border {
	background: white;
	color: #FC4735;
	border: 1rpx solid #FC4735;
	border-radius: 6rpx;
	padding: 8rpx 16rpx;
	font-size: 24rpx;
}

/* 已下架特殊布局 */
.delisted-container {
	margin: 20rpx;
}

.delisted {
	margin-bottom: 0;
	border-bottom: 1rpx dashed #ccc;
}

.delisted:last-child {
	border-bottom: none;
}

.delisted-actions {
	display: flex;
	justify-content: flex-end;
	gap: 16rpx;
	padding: 16rpx 24rpx;
}

.btn.success-border {
	background: white;
	color: #40BDA3;
	border: 1rpx solid #40BDA3;
	border-radius: 6rpx;
	padding: 8rpx 16rpx;
	font-size: 24rpx;
}

/* 草稿箱特殊布局 */
.draft-container {
	margin: 20rpx;
}

.draft {
	margin-bottom: 0;
	border-bottom: 1rpx dashed #ccc;
}

.draft:last-child {
	border-bottom: none;
}

.draft-actions {
	display: flex;
	justify-content: flex-end;
	gap: 16rpx;
	padding: 16rpx 24rpx;
}

.group-container {
	background-color: #fff;
	border-radius: 10px;

}

.no-data {
	display: flex;
	flex-direction: column;
	justify-content: center;
	gap: 20rpx;
}

.no-data-btn {
	color: v-bind(headerColor);
	padding: 20rpx;
	background-color: v-bind(bgColor);
	border-radius: 20rpx;
}
</style>